import { apiClient, apiRoutes } from "../../utils/api";

// pages/Homepage/Homepage.js
Page({
  /**
   * 页面的初始数据 
   */
  data: {
    username: "",
    orgname: "",
    role: "",
    weather: {
      temp: "--",
      windDir: "--",
      windScale: "--",
      humidity: "--",
      pressure: "--",
      uvIndex: "--",
      icon: "/images/weather-icons/default.svg"
    }
  },

  /**
   * 切换角色
   */
  changeRole(e) {
    const role = e.currentTarget.dataset.role;
    const id = wx.getStorageSync("userid");

    apiClient.patch(apiRoutes.users + id + "/", { role: role }).then(res => {
      wx.setStorageSync("role", res.data.role);
      this.setData({ role: res.data.role });
    });
  },

  /**
   * 退出登录
   */
  logout() {
    wx.redirectTo({
      url: "/pages/login/login"
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 判断登录状态
    const username = wx.getStorageSync("username");
    const orgname = wx.getStorageSync("orgname");
    const token = wx.getStorageSync("accessToken");
    const role = wx.getStorageSync("role");

    if (token && orgname && role) {
      this.setData({
        orgname: orgname,
        role: role,
        username: username
      });
    } else {
      wx.navigateTo({
        url: "/pages/login/login"
      });
    }

    // 加载天气数据
    // this.getWeather();
  },

  /**
   * 获取天气数据
   */
  getWeather() {
    const _this = this;

    // 检查授权情况
    wx.getSetting({
      success(res) {
        console.log("用户授权情况:", res.authSetting);
        if (!res.authSetting["scope.userLocation"]) {
          wx.authorize({
            scope: "scope.userLocation",
            success() {
              console.log("用户已授权定位");
              _this.fetchWeatherData(); // 授权后获取天气数据
            },
            fail() {
              console.warn("用户拒绝授权定位");
              wx.showModal({
                title: "定位权限未开启",
                content: "请在微信设置中允许小程序获取位置信息，否则无法获取天气信息。",
                showCancel: true,
                confirmText: "去设置",
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success(settingRes) {
                        if (settingRes.authSetting["scope.userLocation"]) {
                          wx.showToast({ title: "权限已开启", icon: "success" });
                          _this.fetchWeatherData(); // 重新获取天气
                        } else {
                          wx.showToast({ title: "仍未授权", icon: "error" });
                        }
                      }
                    });
                  }
                }
              });
            }
          });
        } else {
          _this.fetchWeatherData(); // 用户已授权，直接获取天气
        }
      },
      fail(err) {
        console.error("获取用户设置信息失败:", err);
      }
    });
  },

  /**
   * 执行天气数据请求
   */
  fetchWeatherData() {
    const _this = this;
    wx.getLocation({
      type: "wgs84",
      success(res) {
        console.log("获取到定位:", res);
        const lat = res.latitude;
        const lon = res.longitude;
        const apiKey = "30c131ff92b3423786bb0e6428e1e582"; // 请替换为你的和风天气 API Key

        // 获取当前天气
        wx.request({
          url: `https://devapi.qweather.com/v7/weather/now?location=${lon},${lat}&key=${apiKey}`,
          success(response) {
            if (response.data.code === "200") {
              _this.updateWeather(response.data.now);
            } else {
              console.error("天气数据请求失败: ", response.data);
              wx.showToast({ title: "天气获取失败", icon: "none" });
            }
          },
          fail(err) {
            console.error("天气数据获取失败:", err);
            wx.showToast({ title: "天气请求失败", icon: "none" });
          }
        });

        // 获取紫外线指数
        wx.request({
          url: `https://devapi.qweather.com/v7/indices/1d?type=5&location=${lon},${lat}&key=${apiKey}`,
          success(response) {
            if (response.data.code === "200" && response.data.daily.length > 0) {
              _this.setData({
                "weather.uvIndex": response.data.daily[0].level
              });
            } else {
              console.warn("紫外线指数获取失败: ", response.data);
            }
          },
          fail(err) {
            console.error("空气质量数据获取失败:", err);
          }
        });
      },
      fail(err) {
        console.error("获取定位失败:", err);
        wx.showModal({
          title: "定位失败",
          content: "错误信息：" + err.errMsg + "\n请确保已开启微信定位权限，并允许小程序访问您的位置。",
          showCancel: false
        });
      }
    });
  },

  /**
   * 处理天气数据，并更新 UI
   */
  updateWeather(data) {
    let iconCode = data.icon;
    let iconUrl = iconCode
      ? `https://icons.qweather.com/assets/icons/${iconCode}.png`
      : "/images/default.svg"; // 备用默认图标

    this.setData({
      weather: {
        temp: data.temp,
        windDir: data.windDir,
        windScale: data.windScale,
        humidity: data.humidity,
        pressure: data.pressure,
        uvIndex: this.data.weather.uvIndex, // 确保紫外线指数不会被覆盖
        icon: iconUrl
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getWeather();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});